<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="作业名称" prop="jobName">
        <el-input
            v-model="queryParams.jobName"
            placeholder="请输入作业名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddFlinkTask"
            v-hasPermi="['resource:job:add']"
        >新增Flink作业
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddFlinkSql"
            v-hasPermi="['resource:job:add']"
        >新增Sql作业
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList(false)"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange" border highlight-current-row
              align="center">
      <el-table-column label="主键ID" align="center" prop="id"/>
      <el-table-column label="项目名称" align="center" prop="applicationName"/>
      <el-table-column label="作业名称" align="center" prop="jobName"/>
      <el-table-column label="yarnId" align="center" prop="yarnId"/>
      <el-table-column label="作业类型" align="center" prop="jobType"/>
      <el-table-column label="运行模式" align="center" prop="deployModel"/>
      <el-table-column label="flink版本" align="center" prop="flinkVersion"/>
      <el-table-column label="作业运行状态" align="center" prop="jobState">
        <template slot-scope="scope">
          <jobStateView option="state" :data="scope.row"></jobStateView>
        </template>
      </el-table-column>
      <el-table-column label="作业发布状态" align="center" prop="deployState">
        <template slot-scope="scope">
          <jobStateView option="deploy" :data="scope.row"></jobStateView>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <!--        <template slot-scope="scope">-->
        <!--          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>-->
        <!--        </template>-->
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <!--        <template slot-scope="scope">-->
        <!--          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>-->
        <!--        </template>-->
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="jobId" align="center" prop="flinkJobId"/>
      <el-table-column label="flink URL" align="center" prop="flinkWebUrl">
        <template slot-scope="scope">
          <el-link type="primary" v-if="(scope.row.jobState===7||scope.row.jobState===6)"
                   :href="scope.row.flinkWebUrl"
                   target="_blank" :underline="false">flink界面<i class="el-icon-link el-icon--right"></i></el-link>
        </template>
      </el-table-column>
      <el-table-column label="监控" align="center" prop="flinkMonitor"/>
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="运行时长" align="center" prop="lunchTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
              size="mini"
              type="text"
              icon="el-icon-position"
              @click="handleDeploye(scope.row)"
              v-if="scope.row.deployState===2"
          >发布部署
          </el-button>

          <el-button
              size="mini"
              type="text"
              icon="el-icon-video-play"
              @click="handleStart(scope.row)"
              v-if="scope.row.deployState===0&&(scope.row.jobState===0||scope.row.jobState===11||scope.row.jobState===12||scope.row.jobState===9)"
          >启动作业
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-video-pause"
              @click="handleStop(scope.row)"
              v-if="(scope.row.jobState===7||scope.row.jobState===6)"
          >停止作业
          </el-button>

          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row,'edit')"
              v-hasPermi="['resource:job:edit']"
              v-if="scope.row.deployState!==1&&(scope.row.jobState===0||scope.row.jobState===11||scope.row.jobState===12||scope.row.jobState===19||scope.row.jobState===9)"
          >修改
          </el-button>

          <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="handleUpdate(scope.row,'detail')"
              v-hasPermi="['resource:job:edit']"
          >配置详情
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['resource:job:remove']"
              v-if="scope.row.deployState!==1&&(scope.row.jobState===0||scope.row.jobState===11||scope.row.jobState===12||scope.row.jobState===19||scope.row.jobState===9)"
          >删除
          </el-button>

          <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handelShowErrorLog(scope.row)"
              v-if="scope.row.deployState===-1||scope.row.jobState===9"
          >错误日志查看
          </el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList(false)"
    />

    <el-dialog title="停止作业" :visible.sync="stopDialogVisable"
               :close-on-click-modal="false"
               @close="handelCloseStartDialog" width="600px">
      <stopJobDialog :formData="stopForm" @cancelClick="cancelClick"/>
    </el-dialog>

    <el-dialog title="启动作业" :visible.sync="startJobVisable"
               :close-on-click-modal="false" width="600px">
      <startjobDialog :formData="startJobForm"
                      @startDialogCloseEvent="startDialogCloseEvent"/>
    </el-dialog>


    <el-dialog :title="errorTitle" :visible.sync="showError" width="80%" top="5vh" append-to-body class="scrollbar">
      <pre><code class="hljs" v-html="errorLogContent"></code></pre>
    </el-dialog>


  </div>
</template>

<script>
import {listJob, getJob, delJob, addJob, updateJob, deployejob, startJob, getErrorLogByJobId} from "@/api/resource/job";
import jobStateView from "@/views/resource/job/jobState";
import Swal from "sweetalert2";
import stopJobDialog from "@/views/resource/job/stopJobDialog";
import startjobDialog from "@/views/resource/job/startjobDialog";
import resize from "@/views/dashboard/mixins/resize";


export default {
  name: "Job",
  components: {
    jobStateView, stopJobDialog, startjobDialog
  },
  data() {
    return {
      errorTitle: '作业错误日志',
      showError: false,
      errorLogContent: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作业管理中心表格数据
      jobList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationId: null,
        jobName: null,
        jobType: null,
        deployModel: null,
        flinkVersion: null,
        jobState: null,
        startTime: null,
        endTime: null,
        userId: null,
        lastSubmitTime: null,
        lastCancelTime: null,
        yarnId: null,
        flinkJobId: null,
        flinkWebUrl: null,
        flinkMonitor: null,
        uid: null,
        taskId: null,
        sqlId: null,
        lunchTime: null
      },
      // 表单参数
      stopForm: {
        jobId: '',
        isSavePoint: false,
        savePointPath: '',
        isDrain: false
      },
      stopDialogVisable: false,

      startJobForm: {
        jobId: '',
        jobName: '',
        startModel: 'normal',
        savepointId: '',
        savePointList: [],
        startPath: '',
        allowNonRestoredState: false
      },

      startJobVisable: false
    };
  },
  created() {
    this.getList(false);
  },
  mounted() {
    const timer = window.setInterval(() => this.getList(true), 2000)
    this.$once('hook:beforeDestroy', () => {
      clearInterval(timer)
    })
  },
  methods: {
    /** 查询作业管理中心列表 */
    getList(isTimer) {
      if (!isTimer) {
        this.loading = true;
      }
      listJob(this.queryParams).then(response => {
        this.jobList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList(false);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    startDialogCloseEvent(v) {
      this.startJobVisable = false;
      if (v) {
        this.getList(false)
      }
    },

    handleStart(row) {
      // const param = {'jobId': row.id}
      this.startJobForm.jobName = row.jobName
      this.startJobForm.jobId = row.id;
      this.startJobForm.startModel = 'normal';
      this.startJobForm.savepointId = '';
      this.startJobForm.savePointList = [];
      this.startJobForm.startPath = '';
      this.startJobForm.allowNonRestoredState = false;
      this.startJobVisable = true;

      // startJob(param).then(res => {
      //   this.$message.success('执行启动成功！');
      // })
    },

    handleStop(row) {
      this.clearStopForm();
      this.stopForm.jobId = row.id + '';
      this.stopDialogVisable = true;
    },

    handelCloseStartDialog(stopTag) {
      this.clearStopForm();
      this.stopDialogVisable = false;
      if (stopTag !== undefined && stopTag === 'stop') {
        this.getList(false)
      }

    },
    cancelClick(stopTag) {
      this.handelCloseStartDialog(stopTag);
    },
    clearStopForm() {
      this.stopForm.jobId = '';
      this.stopForm.isSavePoint = false;
      this.stopForm.savePointPath = '';
      this.stopForm.isDrain = false;
    },

    handleDeploye(row) {
      Swal.fire({
        icon: 'success',
        title: 'The current job is deploy',
        showConfirmButton: false,
        timer: 2000
      }).then((r) => {
        deployejob(row.id)
      })

    },
    /** 新增flink任务操作 */
    handleAddFlinkTask() {
      this.$router.push({path: '/resource/job-flink-task/index'});
    },
    /** 新增flinksql任务操作 */
    handleAddFlinkSql() {
      this.$router.push({path: '/resource/job-flink-sql-task/index'});
    },

    /** 修改按钮操作 */
    handleUpdate(row, type) {
      const id = row.id || this.ids
      getJob(id).then(response => {
        const param = {'data': response.data, 'type': type}
        if (response.data.jobType === 'flink') {
          this.$router.push({path: '/resource/job-flink-task/index', query: param});
        } else {
          this.$router.push({path: '/resource/job-flink-sql-task/index', query: param});
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateJob(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList(false);
            });
          } else {
            addJob(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList(false);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除作业管理中心编号为"' + ids + '"的数据项？').then(function () {
        return delJob(ids);
      }).then(() => {
        this.getList(false);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('resource/job/export', {
        ...this.queryParams
      }, `job_${new Date().getTime()}.xlsx`)
    },

    /** 查看错误日志 */
    handelShowErrorLog(row) {
      getErrorLogByJobId(row.id).then(res => {
        if (res.data != null&&res.data.logContent!=null) {
          this.showError = true;
          this.errorLogContent = res.data.logContent;
        } else {
          this.$message.success('请前往yarn上边查看详细的错误日志,yarnID:'+row.yarnId);
        }
      }).catch(err => {
        this.$message.error(err)
      })
    }

  }
};
</script>
